package com.core.cloudcommon.trace;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author =====Lqj=====
 * @className TraceAspect
 * @description 链路追踪AOP切面
 * @create 2024/12/17 10:30
 **/
@Slf4j
@Aspect
@Component
public class TraceAspect {

    @Around("@annotation(com.core.cloudcommon.trace.Traceable)")
    public Object traceMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Traceable traceable = method.getAnnotation(Traceable.class);

        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = method.getName();
        String operation = traceable.operation().isEmpty() ? 
                className + "." + methodName : traceable.operation();
        String description = traceable.description().isEmpty() ? 
                "执行方法: " + operation : traceable.description();

        long startTime = System.currentTimeMillis();
        Object result = null;
        Throwable exception = null;

        try {
            // 记录开始日志
            if (traceable.logParams()) {
                Object[] args = joinPoint.getArgs();
                String params = args.length > 0 ? JSON.toJSONString(args) : "无参数";
                logByLevel(traceable.level(), "开始执行 - 操作: {}, 描述: {}, 参数: {}", 
                          operation, description, params);
            } else {
                logByLevel(traceable.level(), "开始执行 - 操作: {}, 描述: {}", 
                          operation, description);
            }

            // 执行目标方法
            result = joinPoint.proceed();

            return result;

        } catch (Throwable e) {
            exception = e;
            throw e;
        } finally {
            long elapsedTime = System.currentTimeMillis() - startTime;

            // 记录结束日志
            if (exception != null) {
                // 执行失败
                TraceLogger.error("执行失败 - 操作: {}, 描述: {}, 异常: {}, 耗时: {}ms", 
                                operation, description, exception.getMessage(), elapsedTime);
            } else {
                // 执行成功
                if (traceable.logResult()) {
                    String resultStr = result != null ? JSON.toJSONString(result) : "无返回值";
                    if (elapsedTime > traceable.slowThreshold()) {
                        TraceLogger.warn("执行完成(慢操作) - 操作: {}, 描述: {}, 结果: {}, 耗时: {}ms", 
                                       operation, description, resultStr, elapsedTime);
                    } else {
                        logByLevel(traceable.level(), "执行完成 - 操作: {}, 描述: {}, 结果: {}, 耗时: {}ms", 
                                 operation, description, resultStr, elapsedTime);
                    }
                } else {
                    if (elapsedTime > traceable.slowThreshold()) {
                        TraceLogger.warn("执行完成(慢操作) - 操作: {}, 描述: {}, 耗时: {}ms", 
                                       operation, description, elapsedTime);
                    } else {
                        logByLevel(traceable.level(), "执行完成 - 操作: {}, 描述: {}, 耗时: {}ms", 
                                 operation, description, elapsedTime);
                    }
                }
            }

            // 记录性能日志
            if (traceable.logElapsedTime()) {
                TraceLogger.performance(operation, elapsedTime, 
                                      traceable.logParams() ? joinPoint.getArgs() : null);
            }
        }
    }

    /**
     * 根据级别记录日志
     */
    private void logByLevel(Traceable.LogLevel level, String message, Object... args) {
        switch (level) {
            case DEBUG:
                TraceLogger.debug(message, args);
                break;
            case WARN:
                TraceLogger.warn(message, args);
                break;
            case ERROR:
                TraceLogger.error(message, args);
                break;
            default:
                TraceLogger.info(message, args);
                break;
        }
    }
}
